package com.yinxing.webapi.code.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yinxing.framework.domain.R;
import com.yinxing.webapi.code.entity.sys.SysLog;
import com.yinxing.webapi.code.entity.sys.SysLogDetail;
import com.yinxing.webapi.code.service.sys.ISysLogService;
import com.yinxing.webapi.code.service.sys.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/SysLogController")
public class SysLogController {

    @Autowired
    private ISysLogService service;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 分页查询
     * @param page 分页模型(url?page=1&limit=20)
     * @param params 查询参数 url?page=1&limit=20&key1=value1&key2=value2
     */
    @GetMapping("/selectPage")
    public R selectPage(Page<SysLog> page, @RequestParam Map<String,String> params) {
        QueryWrapper<SysLog> qw = new QueryWrapper<>();
        final String queryParam = "QueryParam_";

        //条件查询
        if(params.containsKey(queryParam)) {
            String queryValue = params.get(queryParam);
            //查询用户ID集合
            List<Long> userIdList = sysUserService.selectUserIdsByUserName(queryValue);

            //条件查询 RequestUrl_ = ? or UserId_ = ? or UserId_ in (???)
            qw.eq("RequestUrl_", queryValue)
                    .or().eq("UserId_", queryValue);
            if(!userIdList.isEmpty()) {
                qw.or().in("UserId_", userIdList);
            }
        }

        //日期范围查询
        if(params.containsKey("LogTimeBegin_")) {
            qw.ge("Date(LogTime_)", params.get("LogTimeBegin_"));
        }
        if(params.containsKey("LogTimeEnd_")) {
            qw.le("Date(LogTime_)", params.get("LogTimeEnd_"));
        }

        qw.orderByDesc("Id_");
        IPage<SysLog> iPage = service.selectMyPage(page, qw);
        return R.ok(iPage);
    }

    /**
     * 主键查询
     * @param id 主键
     */
    @GetMapping("/selectById")
    public R selectById(@RequestParam Long id) throws Exception {
        SysLogDetail record = service.selectDetailById(id);
        return R.ok(record);
    }

    /**
     * 主键删除
     * @param id 主键
     */
    @PostMapping("/deleteById")
    public R deleteById(@RequestParam Long id) {
        service.deleteById(id);
        return R.ok();
    }

    /**
     * 主键批量删除
     * @param ids 主键
    */
    @PostMapping("/deleteBatchById")
    public R deleteBatchById(Long[] ids) {
        service.deleteBatchById(ids);
        return R.ok();
    }

}
